<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { CustomDialogInstance } from '@/types'
import { useIndicatorDataCurve } from './composable'

const emits = defineEmits<{
  (e: 'saveSuccess'): void
}>()
const dialogRef = ref<CustomDialogInstance>()
const formRef = ref<FormInstance>()

const info = defineModel<{
  indicatorName: string
  indicatorNumber: string
  unit: string
  indicatorCode: string
  time: string
  value: number
}>({ required: true })

const rules: FormRules = {
  value: [{ required: true, message: '必填项' }],
}
const { updateRealTimeData } = useIndicatorDataCurve()

async function clickSave(done?: () => void) {
  const isValid = await formRef.value?.validate().catch(() => {})
  if (!isValid) {
    done?.()
    return
  }
  const t = unref(info)
  try {
    await updateRealTimeData({
      indicatorCode: t.indicatorCode,
      time: t.time,
      value: t.value,
    })
    ElMessage.success('修改成功')
    done?.()
    close()
    emits('saveSuccess')
  }
  catch (e) {
    console.warn(e)
  }
  finally {
    done?.()
  }
}

function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="修改实时数据"
    :no-max-height="true"
    width="600px"
    @confirm="clickSave"
  >
    <ElForm
      ref="formRef"
      :model="info" :rules="rules" label-width="100px"
      label-suffix=":"
    >
      <ElFormItem label="指标编码">
        {{ info.indicatorNumber }}
      </ElFormItem>
      <ElFormItem label="指标名称">
        {{ info.indicatorName }}
      </ElFormItem>
      <ElFormItem label="单位">
        {{ info.unit }}
      </ElFormItem>
      <ElFormItem label="测点点位号">
        {{ info.indicatorCode }}
      </ElFormItem>
      <ElFormItem label="时间">
        {{ info.time }}
      </ElFormItem>
      <ElFormItem label="数值" prop="value">
        <ElInputNumber v-model="info.value" class="!w-[200px]" placeholder="请输入数值" />
      </ElFormItem>
    </ElForm>
  </CustomDialog>
</template>
